/*
 * @(#) CommonFunctions.java
 *Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */
package in.ac.dei.edrp.purchase.utilities;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.ibatis.sqlmap.client.SqlMapClient;


/**
 * File Contains Common Methods
 * @author Devendra Singhal
 * @date April 02 2013
 */
public class CommonFunctions {
	//Logger Object to Maintain Log File
	private static Logger logObj = Logger.getLogger(CommonFunctions.class);	
	
	private SqlMapClient sqlMap;
	
	public CommonFunctions(SqlMapClient sqlMap){
		this.sqlMap = sqlMap;
	}
	
	/**
	 * Method to generate Numeric Id's
	 * @param String organizationId
	 * @param String VCode
	 * @return String value
	 **/
	@SuppressWarnings("unchecked")
	synchronized public String generateNumericIds(String organizationId,String VCode){
		String Vno="";
		try{
			UtilityBean inputBean = new UtilityBean();
			inputBean.setOrganizationId(organizationId);
			List<String> list = new ArrayList<String>();
			list.add(VCode);
			inputBean.setList(list);
			List<UtilityBean> vNoList = new ArrayList<UtilityBean>();
			vNoList = sqlMap.queryForList("utility.getSystemId", inputBean);
			String codeValue = vNoList.get(0).getValue();
			String missingCodeValue = vNoList.get(0).getMissingCodes();
			if(missingCodeValue == null || missingCodeValue.equals("")){
				long value = Long.parseLong(codeValue);
				value = value + 1;				
				Vno = String.format("%0"+codeValue.length()+"d", value);							
			}
			else{
				String [] arr = missingCodeValue.split(",");
				Vno = arr[0];	
			}
		}
		catch(Exception e){
			logObj.error("Exception in  generateVoucherNumber method of CommonFunctions class : "+e);
		}
		return Vno;
	}
	
	/**
	 * Method to update System Id's for add and delete records
	 * @param String organizationId
	 * @param String VCode
	 * @param String value
	 * @param String flag
	 * @param boolean zeroFill
	 **/
	
	@SuppressWarnings("unchecked")
	synchronized public void updateNumericSystemId(String organizationId, String VCode, String idValue, String flag, boolean zeroFill){		
		try {
			UtilityBean inputBean = new UtilityBean();
			inputBean.setOrganizationId(organizationId);
			List<String> list = new ArrayList<String>();
			list.add(VCode);
			inputBean.setList(list);
			List<UtilityBean> vNoList = new ArrayList<UtilityBean>();
			vNoList = sqlMap.queryForList("utility.getSystemId", inputBean);			
			String missingCodeValue = vNoList.get(0).getMissingCodes();
			inputBean.setIdCode(VCode);
			//Update System Id's In case of add new Record
			if(flag.equalsIgnoreCase("add")){
				if(missingCodeValue == null || missingCodeValue.equals("")){
					inputBean.setValue(idValue);												
				}
				else{
					String missingCode = null;					
					StringTokenizer  token = new StringTokenizer(missingCodeValue, ",");					
					while(token.hasMoreTokens()){	
						String str = token.nextToken();
						if(!str.equalsIgnoreCase(idValue) && !str.equals("")){
							missingCode = missingCode + str + ",";
						}						
					}
					inputBean.setValue(vNoList.get(0).getValue());
					inputBean.setMissingCodes(missingCode);					
				}
				sqlMap.update("utility.updateSystemId", inputBean);				
			}
			//Update System Id's In case of delete Record
			else if(flag.equalsIgnoreCase("delete")){
				if(Integer.parseInt(vNoList.get(0).getValue().toString()) == Integer.parseInt(idValue)){
					long value = Long.parseLong(idValue);
					value = value - 1;		
					String Vno = "";
					if(zeroFill){
						 Vno = String.format("%0"+idValue.length()+"d", value);
					}
					else{
						 Vno = String.valueOf(value);
					}
					inputBean.setValue(Vno);
					if(missingCodeValue == null || missingCodeValue.equals("")){						
						inputBean.setMissingCodes(null);							
					}
					else{						
						String missingCode = vNoList.get(0).getMissingCodes();	
						inputBean.setMissingCodes(missingCode);
					}
				}
				else{
					if(missingCodeValue == null || missingCodeValue.equals("")){						
						inputBean.setMissingCodes(idValue);	
						inputBean.setValue(vNoList.get(0).getValue());
					}
					else{
						inputBean.setValue(vNoList.get(0).getValue());
						String missingCode = vNoList.get(0).getMissingCodes() + "," + idValue;	
						inputBean.setMissingCodes(missingCode);
					}
				}				
				sqlMap.update("utility.updateSystemId", inputBean);	
			}
			
		} catch (Exception e) {
			logObj.error("Exception in  updateSystemId method of CommonFunctions class : "+e);
		}
	}
}
